package org.epidroid.epidroid.epirss;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class RssDbAdaptater
{
    private static final String DATABASE_NAME = "epidroid_epirss";
    private static final int DATABASE_VERSION = 2;
    private static final String TAG = "RssDbAdaptater";
    
    private final Context mCtx;
    private DatabaseHelper mDbHelper;
    private SQLiteDatabase mDb;

    /**
     * Database creation: create the database when first started and update it if necessary
     */
    private static final String DATABASE_CREATE =
		"CREATE TABLE article (" +
			"id integer primary key autoincrement," +
			"title text not null," +
			"url text not null," +
			"desc text not null," +
			"published datetime not null," +
			"content text not null" +
		");";
    private static class DatabaseHelper extends SQLiteOpenHelper
    {
        DatabaseHelper(Context context)
        {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db)
        {
            db.execSQL(DATABASE_CREATE);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
        {
            Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                    + newVersion + ", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS article");
            onCreate(db);
        }
    }

    /**
     * Constructor - takes the context to allow the database to be
     * opened/created
     * 
     * @param ctx the Context within which to work
     */
    public RssDbAdaptater(Context ctx)
    {
        this.mCtx = ctx;
    }
    

    /**
     * Open the notes database. If it cannot be opened, try to create a new
     * instance of the database. If it cannot be created, throw an exception to
     * signal the failure
     * 
     * @return this (self reference, allowing this to be chained in an
     *         initialization call)
     * @throws SQLException if the database could be neither opened or created
     */
    public RssDbAdaptater open() throws SQLException
    {
        mDbHelper = new DatabaseHelper(mCtx);
        mDb = mDbHelper.getWritableDatabase();
        return this;
    }
    
    public void close()
    {
        mDbHelper.close();
    }


    /**
     * Create a new article, if successfully created return its new rowId otherwise return
     * -1 to indicate failure.
     */
    public long createArticle(RssArticle article)
    {
        ContentValues args = new ContentValues();
        args.put("title", article.title);
        args.put("url", article.url);
        args.put("desc", article.desc);
        args.put("published", article.published);
        args.put("content", article.content);

        return mDb.insert("article", null, args);
    }

    /**
     * Update the article using the details provided.
     */
    public boolean updateArticle(RssArticle article)
    {
        ContentValues args = new ContentValues();
        args.put("title", article.title);
        args.put("desc", article.desc);
        args.put("published", article.published);
        args.put("content", article.content);

        return (mDb.update("article", args, "url = ?", new String[] {article.url})) > 0;
    }

    /**
     * Delete the an article with the given rowId
     * 
     * @param rowId id of article to delete
     * @return true if deleted, false otherwise
     */
    public boolean deleteArticle(long rowId)
    {
        return mDb.delete("article", "id = " + rowId, null) > 0;
    }

    /**
     * Delete all articles
     *
     * @return true if deleted, false otherwise
     */
    public boolean deleteAllArticles()
    {
        return mDb.delete("article", null, null) > 0;
    }

    /**
     * Return a Cursor over the list of all articles in the database
     * 
     * @return Cursor over all articles
     */
    public Cursor fetchAllArticles()
    {
    	Cursor mCursor = mDb.query("article", new String[] {"id", "title", "url", "published"}, null, null, null, null, "published DESC");
        if (mCursor != null)
            mCursor.moveToFirst();
        return mCursor;
    }

    /**
     * Return a Cursor positioned at the article that matches the given title
     * 
     * @param rowid id of article to retrieve
     * @return Cursor positioned to matching article, if found
     * @throws SQLException if article could not be found/retrieved
     */
    public Cursor fetchArticle(int rowid) throws SQLException
    {
        Cursor mCursor = mDb.query(true, "article", new String[] {"id", "title", "url", "desc", "published", "content"},
        		"id = " + rowid, null, null, null, null, null);
        if (mCursor != null)
            mCursor.moveToFirst();
        return mCursor;
    }

    /**
     * Check if an article exist based on the url given
     * 
     * @param link link of article to check
     * @return Cursor positioned to matching article, if found
     * @throws SQLException if article could not be found/retrieved
     */
    public boolean existsArticle(RssArticle article) throws SQLException
    {
        Cursor mCursor = mDb.rawQuery("SELECT COUNT(*) as nb FROM article WHERE url = ?", new String[] {article.url});
        
        boolean exists = false;
        if (mCursor != null)
        {
        	mCursor.moveToFirst();
        	if (mCursor.getCount() >= 1)
        		exists = mCursor.getShort(0) >= 1;
            mCursor.close();
        }
        return exists;
    }
}
